<script setup>
import {ref} from "vue";
import LeftMenu from '@/components/leftmenu.vue'
import avatar from '@/assets/images/avatar.png'
import {useThemeStore} from '@/stores/theme.js'
import {storeToRefs} from "pinia";
import {useAdminStore} from "@/stores/admin.js";
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";
import {getConfig, updateConfig} from "@/api/config.js";
import {getAdminInfo} from "@/api/common.js";

const adminStore = useAdminStore();
const themeStore = useThemeStore();
const router = useRouter();
const {theme} = storeToRefs(themeStore)
const html = document.querySelector('html')
//主题色
const color1 = ref('')
//主题背景色
const color2 = ref('')
//文字颜色
const color3 = ref('')
//设置颜色
const settingColor = () => {
  color1.value = getComputedStyle(html).getPropertyValue("--theme--primary-color")
  color2.value = getComputedStyle(html).getPropertyValue("--theme--bg-primary-color")
  color3.value = getComputedStyle(html).getPropertyValue("--el-text-color")
}
//打开设置
const openSetting = () => {
  settingColor()
  isSetting.value = true
}
//提交主题
const submit = async () => {
  const newTheme = {
    key: Math.random().toString(36).substring(2) + Math.random().toString(36).substring(2),
    themePrimaryColor: color1.value,
    themeBgPrimaryColor: color2.value,
    elTextColor: color3.value,
  }
  const {code, msg} = await updateConfig('theme', [...theme.value.themes, newTheme])
  if (code !== 200) {
    ElMessage.error(msg)
    return
  }
  window.location.reload();
  isSetting.value = false
}
//应用名
const app_title = import.meta.env.VITE_APP_NAME
//是否在设置主题
const isSetting = ref(false)
//当前主题
const current_theme = ref(theme.value.current_theme)
//切换到下一个主题
const chose_theme = () => {
  const themes = theme.value.themes.map(item => item.key);
  const current_theme_index = themes.indexOf(current_theme.value);

  // 获取下一个主题的索引
  const next_theme_index = (current_theme_index + 1) % themes.length;

  // 更新当前主题
  current_theme.value = themes[next_theme_index];
  themeStore.changeTheme(current_theme.value);

  enable_theme()
}
// 应用主题样式
const enable_theme = () => {
  let next_theme = theme.value.themes.find(item => item.key === current_theme.value);
  if (!next_theme) next_theme = theme.value.themes[0];
  document.querySelector('html').className = next_theme.className || 'theme';
  if (next_theme.className) {
    html.style = undefined;
  } else {
    html.style.setProperty("--theme--primary-color", next_theme.themePrimaryColor);
    html.style.setProperty("--theme--bg-primary-color", next_theme.themeBgPrimaryColor);
    html.style.setProperty("--el-text-color", next_theme.elTextColor);
  }
}
//退出登录
const logout = () => {
  adminStore.resetAdmin();
  ElMessage.success('退出成功')
  setTimeout(() => {
    router.replace('/login')
  }, 1000)
}
//选择主题
const choseTheme = (theme) => {
  current_theme.value = theme;
  themeStore.changeTheme(current_theme.value);
  enable_theme();
  settingColor();
}
//删除主题
const delTheme = (key) => {
  ElMessageBox.confirm(
      '确定删除选中主题吗？',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const {code, msg} = await updateConfig('theme', theme.value.themes.filter(item => item.key !== key))
        if (code !== 200) {
          ElMessage.error(msg)
          return
        }
        window.location.reload();
      })
      .catch(() => {
        ElMessage.info('已取消');
      })
}
//初始化
const init = async () => {
  const {data: theme} = await getConfig('theme')
  const {data: admin} = await getAdminInfo()
  adminStore.setAdmin(admin)
  themeStore.setThemes(theme)
  enable_theme()
}
init()
</script>

<template>
  <el-container>
    <!--左侧菜单-->
    <el-aside class="aside" :style="{width:theme.isCollapse ?'60px':`200px`}">
      <div class="title">
        <b v-if="!theme.isCollapse">{{ app_title || '后台管理系统' }}</b>
        <el-avatar v-else
                   :src="adminStore.admin.avatar || avatar"
        />
      </div>
      <LeftMenu :is-collapse="theme.isCollapse" :menu="adminStore.admin.menus"/>
    </el-aside>
    <el-container>
      <el-header class="header">
        <div class="left">
          <el-icon size="20" @click="themeStore.changeCollapse()">
            <Expand v-if="theme.isCollapse"/>
            <Fold v-else/>
          </el-icon>
        </div>
        <div class="right">
          <div @click="ElMessage.success('已刷新缓存')">
            <el-icon>
              <Refresh/>
            </el-icon>
          </div>
          <div @click="ElMessage.success('响应成功')">
            <el-icon>
              <Bell/>
            </el-icon>
          </div>
          <div class="dropdown">
            <el-dropdown trigger="click">
              <template #default>
                <div>
                  {{ adminStore.admin.nickname ?? '菜单' }}
                  <el-icon>
                    <arrow-down/>
                  </el-icon>
                </div>
              </template>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="chose_theme">切换主题</el-dropdown-item>
                  <el-dropdown-item @click="openSetting">设置主题</el-dropdown-item>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <div class="content">
        <el-main class="main">
          <RouterView/>
        </el-main>
      </div>
    </el-container>
  </el-container>


  <el-dialog v-model="isSetting" center title="自定义主题颜色" width="400" style="background-color:#ccc;">
    <div style="display: flex;justify-content: space-around">
      <div class="setting-left">
        <span v-for="item in theme.themes">
          <el-icon :color="item.themePrimaryColor"
                   @contextmenu.prevent.stop="delTheme(item.key)"
                   @click="choseTheme(item.key)">
            <Monitor/>
          </el-icon>
        </span>
      </div>
      <div>
        <div>系统主体颜色:
          <el-color-picker v-model="color1"/>
        </div>
        <div>系统背景颜色:
          <el-color-picker v-model="color2"/>
        </div>
        <div>系统文字颜色:
          <el-color-picker v-model="color3"/>
        </div>
      </div>
    </div>
    <div style="text-align: center;margin-top: 20px;">
      <el-button type="primary" @click="submit">增加</el-button>
    </div>
  </el-dialog>

</template>

<style scoped lang="scss">
.aside {
  padding-top: 12px;
  height: 100vh;
  background-color: var(--el-menu-bg-color);
  transition: width .3s;

  .title {
    text-align: center;
    line-height: 40px;
    font-size: 18px;
    height: 48px;
    color: var(--el-menu-text-color);
  }
}

.header {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--el-text-color);
  background-color: var(--el-menu-bg-color);

  .right {
    display: flex;
    align-items: center;
    justify-content: center;

    & > div {
      cursor: pointer;
      margin-right: 20px;
    }

    .dropdown {
      cursor: pointer;

      .el-dropdown div:nth-child(1) {
        outline: none;
        color: var(--el-text-color);
      }
    }
  }
}

.content {

  .main {
    padding: 0;
    height: calc(100vh - 60px);
  }
}

.setting-left {
  width: 40%;

  & > span {
    margin: 8px;
    font-size: 18px;
    cursor: pointer;
  }
}
</style>
